package com.newvpn.fastbest.zenith.utils;

import com.newvpn.fastbest.zenith.beans.netbeans.EncryBean;

import java.nio.charset.Charset;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.KeySpec;
import java.security.spec.PKCS8EncodedKeySpec;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class DecryptUtils {

    static {
        System.loadLibrary("keylib");
    }

    public static native String getStr1();

    public static native String getStr2();

    public static native String getStr3();

    public static native String getStr4();

    public static String decodeRSA(String src){
        try {
            String key =  getStr1();
            // 使用 Android 的 Base64 解码器解码私钥
            byte[] decodedKey = android.util.Base64.decode(key, android.util.Base64.DEFAULT);
            KeySpec keySpec = new PKCS8EncodedKeySpec(decodedKey);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
            // 初始化 Cipher 对象用于解密
            Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            // 使用 Android 的 Base64 解码器解码加密的数据
            byte[] decodedData = android.util.Base64.decode(src, android.util.Base64.DEFAULT);
            // 调用自定义方法进行实际的解密操作
            byte[] decryptedData = cipher.doFinal(decodedData);//rsaSplitCodec(cipher, Cipher.DECRYPT_MODE, decodedData);
            // 将解密后的数据转换为字符串
            return new String(decryptedData, Charset.forName("UTF-8"));
        } catch (Exception e) {
            // 打印异常信息，实际开发中可能需要更细致的异常处理
            throw new RuntimeException("解密字符串[" + src + "]时遇到异常", e);
        }
    }

    public static String decodeAES(String passwordDecrypt,String src) {
        try {
            byte[] raw = passwordDecrypt.getBytes("UTF-8");
            SecretKeySpec secretKeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            IvParameterSpec iv = new IvParameterSpec(getStr2().getBytes("UTF-8"));
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, iv);
            byte[] encrypted1 = android.util.Base64.decode(src, android.util.Base64.DEFAULT);
            byte[] original = cipher.doFinal(encrypted1);
            return new String(original, "UTF-8");
        } catch (Exception e) {
            //log.error("aes decrypt exception:", e);
            throw new RuntimeException("aes decrypt exception:", e);
        }
    }


    public static String decode(EncryBean data) {
        String passwordDecrypt = DecryptUtils.decodeRSA(data.password);
        return DecryptUtils.decodeAES(passwordDecrypt, data.content);//"Ho8GkZqbZfGmILvU"
    }

}


